# coding: utf-8
from django.db import models
from lib.common import BasicManager
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from lib.common import CacheKeys
from django.core.cache import cache


class ModelManagerHistoryCache(BasicManager):
    def get_cache_list(self, page, status=None):
        result = self.values().order_by("-created_at")
        if status:
            result = result.filter(status=status)
        if not page:
            return {'retcode': 0, 'retlist': list(result)}
        paginator = Paginator(result, 15)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def add_data(self, name, day, cache_key, cache_value):
        self.create(
            name=name,
            day=day,
            cache_key=cache_key,
            cache_value=cache_value,
        )

    def get_cache_data_for_key(self, key):
        """
        :param key: 缓存的key
        :return: {"data":0} or {"data":None}
        """
        res = cache.get(key)
        if not res:
            result = self.filter(cache_key=key).order_by('-created_at').first()
            if result:
                return {"data": result.cache_value}
        return {"data": res}


class HistoryCache(models.Model):
    name = models.CharField("缓存名称", max_length=50)
    # status = models.PositiveSmallIntegerField("状态", default=1)  #
    day = models.DateField('天')  # 2020-01-17
    cache_key = models.CharField("缓存key", max_length=100, db_index=True)
    cache_value = models.TextField("值", default='')  # 该字段存取int类型和string类型,  int类型为分为单位需要除以100
    # now_cache_value = models.IntegerField("当日当前统计值值", default=0)  # 实际数据取出都要除以100
    # str_val = models.TextField("拼接字符串值", default='')  # 记录一些列表组装的值
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerHistoryCache()

    class Meta:
        verbose_name = '系统历史数据缓存'
        verbose_name_plural = verbose_name
        db_table = "momself_history_cache"

    def __str__(self):
        return self.name


mm_HistoryCache = HistoryCache.objects
